import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import logging
import os
from datetime import datetime
from data_handler import DataHandler
from components import ColumnSelector, ParameterDialog

# 配置日志
logging.basicConfig(
    filename='excel_cleaner.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class ExcelCleaner:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Excel数据格式化工具")
        self.window.geometry("1200x800")
        self.window.configure(bg='#f0f0f0')

        # 初始化数据处理器
        self.data_handler = DataHandler()
        self.current_file = None

        # 创建主界面
        self.create_gui()

    def create_gui(self):
        # 创建主框架
        main_frame = ttk.Frame(self.window)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 左侧工具面板
        left_panel = ttk.LabelFrame(main_frame, text="工具面板", padding=10)
        left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)

        # 文件操作区域
        self.create_file_frame(left_panel)

        # 数据处理操作区域
        self.create_operation_frame(left_panel)

        # 右侧预览区域
        right_panel = ttk.LabelFrame(main_frame, text="数据预览", padding=10)
        right_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 创建预览表格
        self.create_preview_table(right_panel)

        # 创建状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪")
        status_bar = ttk.Label(self.window, textvariable=self.status_var, relief=tk.SUNKEN)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def create_file_frame(self, parent):
        file_frame = ttk.LabelFrame(parent, text="文件操作", padding=5)
        file_frame.pack(fill=tk.X, pady=5)

        ttk.Button(file_frame, text="打开文件", command=self.open_file).pack(fill=tk.X, pady=2)
        ttk.Button(file_frame, text="保存文件", command=self.save_file).pack(fill=tk.X, pady=2)

    def create_operation_frame(self, parent):
        op_frame = ttk.LabelFrame(parent, text="数据处理", padding=5)
        op_frame.pack(fill=tk.X, pady=5)

        operations = [
            ("删除空格", self.remove_spaces),
            ("统一大小写", self.normalize_case),
            ("格式化数字", self.format_numbers),
            ("格式化日期", self.format_dates),
            ("删除特殊字符", self.remove_special_chars),
            ("填充空值", self.fill_empty_values),
            ("删除空行", self.remove_empty_rows)
        ]

        for op_name, op_func in operations:
            ttk.Button(op_frame, text=op_name, command=op_func).pack(fill=tk.X, pady=2)

    def create_preview_table(self, parent):
        # 创建表格框架
        table_frame = ttk.Frame(parent)
        table_frame.pack(fill=tk.BOTH, expand=True)

        # 创建水平和垂直滚动条
        h_scrollbar = ttk.Scrollbar(table_frame, orient=tk.HORIZONTAL)
        v_scrollbar = ttk.Scrollbar(table_frame)
        h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
        v_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        # 创建表格
        self.preview_table = ttk.Treeview(table_frame,
                                         yscrollcommand=v_scrollbar.set,
                                         xscrollcommand=h_scrollbar.set)
        self.preview_table.pack(fill=tk.BOTH, expand=True)

        # 配置滚动条
        h_scrollbar.config(command=self.preview_table.xview)
        v_scrollbar.config(command=self.preview_table.yview)

    def update_preview(self):
        # 清空现有数据
        for item in self.preview_table.get_children():
            self.preview_table.delete(item)

        if self.data_handler.df is not None:
            # 设置列
            self.preview_table['columns'] = list(self.data_handler.df.columns)
            self.preview_table['show'] = 'headings'

            # 设置列标题
            for column in self.data_handler.df.columns:
                self.preview_table.heading(column, text=column)
                self.preview_table.column(column, width=100)

            # 添加数据（限制显示前100行）
            for idx, row in self.data_handler.df.head(100).iterrows():
                self.preview_table.insert('', tk.END, values=list(row))

            # 更新状态栏
            stats = self.data_handler.get_statistics()
            self.status_var.set(
                f"总行数: {stats['row_count']} | 总列数: {stats['column_count']} | "
                f"空值数: {stats['null_count']}")

    def open_file(self):
        try:
            file_path = filedialog.askopenfilename(
                filetypes=[("Excel文件", "*.xlsx;*.xls")]
            )
            if file_path:
                self.current_file = file_path
                self.data_handler.load_excel(file_path)
                self.update_preview()
                messagebox.showinfo("成功", "文件加载成功！")
        except Exception as e:
            messagebox.showerror("错误", str(e))

    def save_file(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "没有数据可保存！")
            return

        try:
            file_path = filedialog.asksaveasfilename(
                defaultextension=".xlsx",
                filetypes=[("Excel文件", "*.xlsx")]
            )
            if file_path:
                self.data_handler.save_excel(file_path)
                messagebox.showinfo("成功", "文件保存成功！")
        except Exception as e:
            messagebox.showerror("错误", str(e))

    def remove_spaces(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

        def on_columns_selected(columns):
            try:
                self.data_handler.remove_spaces(columns)
                self.update_preview()
                messagebox.showinfo("成功", "空格删除成功！")
            except Exception as e:
                messagebox.showerror("错误", str(e))

        ColumnSelector(self.window, 
                      self.data_handler.df.columns,
                      self.data_handler.get_column_types(),
                      "选择要删除空格的列",
                      on_columns_selected)

    def normalize_case(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

        params = {
            'case_type': {
                'label': '大小写类型',
                'type': 'choice',
                'choices': ['lower', 'upper', 'title'],
                'default': 'lower'
            }
        }

        def on_params_set(params_values):
            def on_columns_selected(columns):
                try:
                    self.data_handler.normalize_case(params_values['case_type'], columns)
                    self.update_preview()
                    messagebox.showinfo("成功", "大小写转换成功！")
                except Exception as e:
                    messagebox.showerror("错误", str(e))

            ColumnSelector(self.window,
                          self.data_handler.df.columns,
                          self.data_handler.get_column_types(),
                          "选择要转换大小写的列",
                          on_columns_selected)

        ParameterDialog(self.window, params, "设置大小写转换参数", on_params_set)

    def format_numbers(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

        params = {
            'decimal_places': {
                'label': '小数位数',
                'type': 'int',
                'min': 0,
                'max': 10,
                'default': 2
            }
        }

        def on_params_set(params_values):
            def on_columns_selected(columns):
                try:
                    self.data_handler.format_numbers(params_values['decimal_places'], columns)
                    self.update_preview()
                    messagebox.showinfo("成功", "数字格式化成功！")
                except Exception as e:
                    messagebox.showerror("错误", str(e))

            ColumnSelector(self.window,
                          self.data_handler.df.columns,
                          self.data_handler.get_column_types(),
                          "选择要格式化的数字列",
                          on_columns_selected)

        ParameterDialog(self.window, params, "设置数字格式化参数", on_params_set)

    def format_dates(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

        params = {
            'date_format': {
                'label': '日期格式',
                'type': 'choice',
                'choices': ['%Y-%m-%d', '%Y/%m/%d', '%Y年%m月%d日'],
                'default': '%Y-%m-%d'
            }
        }

        def on_params_set(params_values):
            def on_columns_selected(columns):
                try:
                    self.data_handler.format_dates(params_values['date_format'], columns)
                    self.update_preview()
                    messagebox.showinfo("成功", "日期格式化成功！")
                except Exception as e:
                    messagebox.showerror("错误", str(e))

            ColumnSelector(self.window,
                          self.data_handler.df.columns,
                          self.data_handler.get_column_types(),
                          "选择要格式化的日期列",
                          on_columns_selected)

        ParameterDialog(self.window, params, "设置日期格式化参数", on_params_set)

    def remove_special_chars(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

        params = {
            'pattern': {
                'label': '要删除的字符模式',
                'type': 'str',
                'default': '[^\w\s]'
            }
        }

        def on_params_set(params_values):
            def on_columns_selected(columns):
                try:
                    self.data_handler.remove_special_chars(params_values['pattern'], columns)
                    self.update_preview()
                    messagebox.showinfo("成功", "特殊字符删除成功！")
                except Exception as e:
                    messagebox.showerror("错误", str(e))

            ColumnSelector(self.window,
                          self.data_handler.df.columns,
                          self.data_handler.get_column_types(),
                          "选择要处理的列",
                          on_columns_selected)

        ParameterDialog(self.window, params, "设置特殊字符删除参数", on_params_set)

    def fill_empty_values(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

    def remove_empty_rows(self):
        if self.data_handler.df is None:
            messagebox.showwarning("警告", "请先加载数据！")
            return

        try:
            self.data_handler.remove_empty_rows()
            self.update_preview()
            messagebox.showinfo("成功", "空行删除成功！")
        except Exception as e:
            messagebox.showerror("错误", str(e))

        params = {
            'method': {
                'label': '填充方法',
                'type': 'choice',
                'choices': ['value', 'mean', 'median', 'mode', 'ffill', 'bfill'],
                'default': 'value'
            },
            'value': {
                'label': '填充值（仅用于固定值填充）',
                'type': 'str',
                'default': '0'
            }
        }

        def on_params_set(params_values):
            def on_columns_selected(columns):
                try:
                    self.data_handler.fill_empty_values(
                        method=params_values['method'],
                        value=params_values['value'],
                        columns=columns
                    )
                    self.update_preview()
                    messagebox.showinfo("成功", "空值填充成功！")
                except Exception as e:
                    messagebox.showerror("错误", str(e))

            ColumnSelector(self.window,
                          self.data_handler.df.columns,
                          self.data_handler.get_column_types(),
                          "选择要填充的列",
                          on_columns_selected)

        ParameterDialog(self.window, params, "设置空值填充参数", on_params_set)

    def run(self):
        self.window.mainloop()

if __name__ == '__main__':
    app = ExcelCleaner()
    app.run()